import re

class YaapsField(object):
    def __init__(self, name, required=True, error_message="This is a required"):
        self.name = name
        self.required = required
        self.error_message = error_message

    def validate(self, values):
        return None

class YaapsTextField(YaapsField):
    def validate(self, values):
        if len(values) != 1:
            return "Must have a single value"
        return None

class YaapsIntegerField(YaapsField):
    _rx = re.compile("\d+", re.UNICODE)
    def validate(self, values):
        if len(values) != 1:
            return "Must have a single value"
        if not self._rx.match(values[0]):
            return "Must be a number"
        return None

class YaapsFloatField(YaapsField):
    _rx = re.compile("[+\-]?\d+(.\d+)?", re.UNICODE)
    def validate(self, values):
        if len(values) != 1:
            return "Must have a single value"
        if not self._rx.match(values[0]):
            return "Must be a floating point number"
        return None
        
class YaapsForm(object):
    def __init__(self, values):
        self._values = values
        self.errors = {}

    def validate(self):
        for f in self.fields:
            if f.name not in self._values:
                if f.required:
                    self.errors[f.name] = f.error_message
                    continue
            else:
                validate_message = f.validate(self._values[f.name])
                if validate_message:
                    self.errors[f.name] = validate_message
        return self.errors

    def __getitem__(self, key):
        v = self._values[key]
        v_len = len(v)
        if v_len == 0:
            return None
        elif len(v) == 1:
            return v[0]
        else:
            return v

    def __setitem__(self, key, value):
        self._values[key] = value

    def __delitem__(self, key):
        del self._values[key]
        
    def __contains__(self, key):
        return key in self._values
